import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';

/// 网络状态管理器
class NetworkManager extends GetxController {
  static NetworkManager get instance => Get.find<NetworkManager>();

  /// 网络状态
  final Rx<NetworkStatus> status = NetworkStatus.unknown.obs;

  /// 是否有网络连接
  bool get hasConnection => status.value != NetworkStatus.none;

  /// 网络类型
  String get networkType => _getNetworkType(status.value);

  /// 监听器
  StreamSubscription<List<ConnectivityResult>>? _subscription;

  @override
  void onInit() {
    super.onInit();
    _initNetworkStatus();
  }

  @override
  void onClose() {
    _subscription?.cancel();
    super.onClose();
  }

  /// 初始化网络状态监听
  void _initNetworkStatus() async {
    try {
      // 获取初始网络状态
      List<ConnectivityResult> results = await Connectivity().checkConnectivity();
      _updateNetworkStatus(results);

      // 监听网络状态变化
      _subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> results) {
        _updateNetworkStatus(results);
      });
    } catch (e) {
      LogUtil.e('NetworkManager init error: $e');
      status.value = NetworkStatus.unknown;
    }
  }

  /// 更新网络状态
  void _updateNetworkStatus(List<ConnectivityResult> results) {
    if (results.contains(ConnectivityResult.none)) {
      status.value = NetworkStatus.none;
      LogUtil.v('网络已断开');
    } else if (results.contains(ConnectivityResult.mobile)) {
      status.value = NetworkStatus.mobile;
      LogUtil.v('已切换到移动网络');
    } else if (results.contains(ConnectivityResult.wifi)) {
      status.value = NetworkStatus.wifi;
      LogUtil.v('已切换到WiFi网络');
    } else if (results.contains(ConnectivityResult.ethernet)) {
      status.value = NetworkStatus.ethernet;
      LogUtil.v('已切换到以太网络');
    } else if (results.contains(ConnectivityResult.vpn)) {
      status.value = NetworkStatus.vpn;
      LogUtil.v('已切换到VPN网络');
    } else {
      status.value = NetworkStatus.unknown;
      LogUtil.v('未知网络状态');
    }
  }

  /// 获取网络类型描述
  String _getNetworkType(NetworkStatus status) {
    switch (status) {
      case NetworkStatus.mobile:
        return '移动网络';
      case NetworkStatus.wifi:
        return 'WiFi网络';
      case NetworkStatus.ethernet:
        return '以太网络';
      case NetworkStatus.vpn:
        return 'VPN网络';
      case NetworkStatus.none:
        return '无网络';
      case NetworkStatus.unknown:
        return '未知网络';
    }
  }
}

/// 网络状态
enum NetworkStatus {
  mobile,
  wifi,
  ethernet,
  vpn,
  none,
  unknown,
}

/// 网络状态拦截器
class NetworkStatusInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (!NetworkManager.instance.hasConnection) {
      handler.reject(
        DioException(
          requestOptions: options,
          type: DioExceptionType.connectionError,
          error: '网络异常',
          message: '网络异常，请稍后再试',
        ),
      );
      return;
    }
    handler.next(options);
  }
}
